package com.yiwei.ydd.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.ydd.R;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.bean.BindOrderOilCardBean;
import com.yiwei.ydd.api.bean.OrderDeleteBean;
import com.yiwei.ydd.api.bean.OrderDetailBean;
import com.yiwei.ydd.api.model.OrderDetailModel;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.event.BuyVipUpSuccessEvent;
import com.yiwei.ydd.event.OilcardAddSuccess;
import com.yiwei.ydd.util.Arith;
import com.yiwei.ydd.util.DateTime;
import com.yiwei.ydd.util.Dialog;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.Spans;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.UI;
import com.yiwei.ydd.util.Util;
import com.yiwei.ydd.view.OilChangeDialog;
import com.yiwei.ydd.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class MyOrderDetailActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_status_one)
    TextView txtStatusOne;
    @BindView(R.id.img_status)
    ImageView imgStatus;
    @BindView(R.id.txt_card_type)
    TextView txtCardType;
    @BindView(R.id.txt_status)
    TextView txtStatus;
    @BindView(R.id.img_card_type)
    ImageView imgCardType;
    @BindView(R.id.fl_card_type)
    FrameLayout flCardType;
    @BindView(R.id.txt_content)
    TextView txtContent;
    @BindView(R.id.txt_info_left)
    TextView txtInfoLeft;
    @BindView(R.id.txt_info_right)
    TextView txtInfoRight;
    @BindView(R.id.txt_info_two_left)
    TextView txtInfoTwoLeft;
    @BindView(R.id.txt_info_two_right)
    TextView txtInfoTwoRight;
    //    @BindView(R.id.txt_recharge_detail)
//    TextView txtRechargeDetail;
//    @BindView(R.id.layout_recharge_detail)
//    LinearLayout layoutRechargeDetail;

    @BindView(R.id.txt_order_title)
    TextView txtOrderTitle;
    @BindView(R.id.btn_two)
    SuperButton btnTwo;
    @BindView(R.id.btn_buy)
    SuperButton btnBuy;
    @BindView(R.id.layout_no_card)
    FrameLayout layoutNoCard;
    private OilChangeDialog oilChangeDialog;
    private Unbinder unbiner;
    private int x26;
//    private List<RechargeTermDetailModel.DatasBean> periodsData;

    private String orderMoney;
    private String orderNo;
    private OrderDetailModel.DatasBean totalData;
    //订单类型（1：快速充值，2：分期充值）
    private String rechargeType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order_detail);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BuyVipUpSuccessEvent event) {
        finish();
    }

    public void getOrderDetail(String order_number) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        OrderDetailBean bean = new OrderDetailBean();
        bean.order_number = order_number;
        Api.api_service.getOrderDetail(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setData(result.datas);
                });
    }

    public void getOrderDelete(String order_number) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        OrderDeleteBean bean = new OrderDeleteBean();
        bean.order_no = order_number;
        Api.api_service.getOrderDelete(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "删除成功");
                    finish();
                });
    }

    private void setData(OrderDetailModel.DatasBean datas) {
        totalData = datas;
        orderMoney = datas.pay_money;
        orderNo = datas.order_no;
        rechargeType = datas.type;


//        if (TextUtils.isEmpty(datas.card_number) && datas.status.equals("2")) {
//            txtCardType.setText("请在48小时内添加加油卡");
//            layoutNoCard.setVisibility(View.VISIBLE);
//        } else {
//            if (datas.status.equals("0")) {
//                txtCardType.setText("请在24小时内付款");
//            } else {
//                String strsub = "";
//                if (datas.card_number.length() >= 4) {// 判断是否长度大于等于4
//                    strsub = datas.card_number.substring(datas.card_number.length() - 4);//一个参数表示截取传递的序号之后的部分
//                } else {
//                    strsub = datas.card_number;
//                }
//                Spanned cardType = Spans.with(this).font(datas.card_type, getResources().getDimensionPixelSize(R.dimen.x28), 0xff333333).
//                        font("(卡尾号" + strsub + ")", getResources().getDimensionPixelSize(R.dimen.x24), 0xffFB5E01).
//                        build();
//                txtCardType.setText(cardType);
//            }
        if (datas.card_type.contains("石化")) {
            imgCardType.setImageResource(R.mipmap.img_order_shihua);
        } else if (datas.card_type.contains("石油")) {
            imgCardType.setImageResource(R.mipmap.img_order_shiyou);
        }

//        }


        Spanned cardType = Spans.with(this).font(datas.card_type, getResources().getDimensionPixelSize(R.dimen.x28), 0xff333333).style(Typeface.BOLD).
                build();
        txtCardType.setText(cardType);

        txtOrderTitle.setText(datas.name);


//        if (datas.card_type.equals("中国石油")) {
//            imgCardType.setImageResource(R.mipmap.img_type_shiyou);
//        } else if (datas.card_type.equals("中国石化")) {
//            imgCardType.setImageResource(R.mipmap.img_type_shihua);
//        }

        //订单类型（1：快速充值，2：分期充值）
        //订单状态（-2：失效，-1：失败，0：待支付，1：完成，2：已付款，3：分期中）
        switch (datas.status) {
            case "-2":
                imgStatus.setImageResource(R.mipmap.img_status_pay_close);
                if (datas.type.equals("1")) {
                    btnBuy.setVisibility(View.VISIBLE);
                    btnBuy.setText("重新购买");
                    btnTwo.setVisibility(View.VISIBLE);
                    btnTwo.setText("删除订单");
                } else {
                    btnBuy.setVisibility(View.VISIBLE);
                    btnBuy.setText("重新购买");
                    btnTwo.setVisibility(View.VISIBLE);
                    btnTwo.setText("删除订单");
                }
                txtStatus.setText("失效");
                txtStatusOne.setText("交易关闭");
                txtCardType.setText("该订单已失效，请重新购买");
                break;
            case "-1":
                imgStatus.setImageResource(R.mipmap.img_status_pay_close);
                if (datas.type.equals("1")) {
                    btnBuy.setVisibility(View.VISIBLE);
                    btnBuy.setText("重新购买");
                    btnTwo.setVisibility(View.GONE);
                } else {
                    btnBuy.setVisibility(View.VISIBLE);
                    btnBuy.setText("重新购买");
                    btnTwo.setVisibility(View.GONE);
                }
                txtStatus.setText("失败");
                txtStatusOne.setText("交易失败");
                break;
            case "0":
                imgStatus.setImageResource(R.mipmap.img_status_need_pay);
                btnBuy.setVisibility(View.VISIBLE);
                btnBuy.setText("去付款");
                btnTwo.setVisibility(View.GONE);
                txtStatus.setText("待付款");

                String restTime = Util.getRestTime(Long.valueOf(datas.valid_date) * 1000 - new Date().getTime());

                Spanned rest_time = Spans.with(this).font("等待买家付款\n", getResources().getDimensionPixelSize(R.dimen.x32), 0xffffffff).
                        font("剩" + restTime + "自动关闭", getResources().getDimensionPixelSize(R.dimen.x24), 0xffffffff).style(Typeface.BOLD).
                        build();
                txtStatusOne.setText(rest_time);

                txtCardType.setText("请在24小时内付款");
                break;
            case "1":
                imgStatus.setImageResource(R.mipmap.img_status_finish);
                btnBuy.setVisibility(View.VISIBLE);
                btnBuy.setText("再次购买");
                btnTwo.setVisibility(View.GONE);
                txtStatus.setText("已完成");
                txtStatusOne.setText("订单已完成");
                break;
            case "2":
                imgStatus.setImageResource(R.mipmap.img_status_finish);
                if (TextUtils.isEmpty(datas.card_number)) {
                    btnBuy.setVisibility(View.VISIBLE);
                    btnBuy.setText("选择油卡");
                    txtStatus.setText("待加油卡");
                } else {
                    btnBuy.setVisibility(View.VISIBLE);
                    btnBuy.setText("再次购买");
                    txtStatus.setText("已付款");
                }
//                btnBuy.setVisibility(View.VISIBLE);
//                btnBuy.setText("再次购买");
                btnTwo.setVisibility(View.VISIBLE);
                btnTwo.setText("联系客服");

                txtStatusOne.setText("已付款");
                if (TextUtils.isEmpty(datas.card_number)) {
                    layoutNoCard.setVisibility(View.VISIBLE);
                    txtCardType.setText("请在48小时内添加加油卡");
                }

                break;
            case "3":
                imgStatus.setImageResource(R.mipmap.img_status_finish);
                if (datas.type.equals("1")) {
                    btnBuy.setVisibility(View.GONE);
                } else {
                    if (TextUtils.isEmpty(datas.card_number)) {
                        btnBuy.setVisibility(View.VISIBLE);
                        btnBuy.setText("选择油卡");
                        txtStatus.setText("待加油卡");
                    } else {
                        btnBuy.setVisibility(View.VISIBLE);
                        btnBuy.setText("返现记录");
                        txtStatus.setText("加油中");
                    }

                }
                btnTwo.setVisibility(View.VISIBLE);
                btnTwo.setText("联系客服");

                txtStatusOne.setText("返现加油中");
                if (TextUtils.isEmpty(datas.card_number)) {
                    txtCardType.setText("请在48小时内添加加油卡");
                }
                break;
        }

        if (datas.status.equals("2") || datas.status.equals("1") || datas.status.equals("3")) {
            Spanned infoTwoLeft = Spans.with(this).font("订单编号", x26, 0xff999999).
                    font("\n下单时间", x26, 0xff999999).
                    font("\n支付方式", x26, 0xff999999).
                    font("\n支付时间", x26, 0xff999999).
                    build();
            txtInfoTwoLeft.setText(infoTwoLeft);
            Spanned infoTwoRight = Spans.with(this).font(datas.order_no, x26, 0xff999999).
                    font("\n" + DateTime.toDateTime(Long.valueOf(datas.created_at) * 1000), x26, 0xff999999).
                    font("\n" + datas.pay_way, x26, 0xff999999).
                    font("\n" + DateTime.toDateTime(Long.valueOf(datas.pay_date) * 1000), x26, 0xff999999).
                    build();
            txtInfoTwoRight.setText(infoTwoRight);
        } else {
            Spanned infoTwoLeft = Spans.with(this).font("订单编号", x26, 0xff999999).
                    font("\n下单时间", x26, 0xff999999).
                    build();
            txtInfoTwoLeft.setText(infoTwoLeft);
            Spanned infoTwoRight = Spans.with(this).font(datas.order_no, x26, 0xff999999).
                    font("\n" + DateTime.toDateTime(Long.valueOf(datas.created_at) * 1000), x26, 0xff999999).
                    build();
            txtInfoTwoRight.setText(infoTwoRight);
        }

        String first_time = "";
        if (datas.periods_detail != null && datas.periods_detail.size() != 0) {
            first_time = datas.periods_detail.get(0).get_date;
        } else {
            first_time = "2至48小时内到账";
        }

        if (datas.type.equals("1")) {
//        ===================================================快速充值===================================================
//            layoutRechargeDetail.setVisibility(View.GONE);
            Spanned money = Spans.with(this).font("￥" + datas.pay_money, getResources().getDimensionPixelSize(R.dimen.x32), 0xffFB5E01).style(Typeface.BOLD).
                    font(" " + Arith.mul(Float.valueOf(datas.sale), 0.1) + "折", getResources().getDimensionPixelSize(R.dimen.x22), 0xff999999).
                    build();
            txtContent.setText(money);
            Spanned infoLeft = Spans.with(this).font("加油卡卡号", x26, 0xff999999).
                    font("\n套餐时长", x26, 0xff999999).
                    font("\n首笔到账时间", x26, 0xff999999).
                    font("\n每月应得", x26, 0xff999999).
                    font("\n加油包", x26, 0xff999999).
                    font("\n每月多赠送", x26, 0xff999999).
                    font("\n折扣幅度", x26, 0xff999999).
                    font("\n应到账总额", x26, 0xff999999).
                    font("\n应付金额", x26, 0xff999999).
                    font("\n实际付款金额", x26, 0xff333333).
                    build();
            txtInfoLeft.setText(infoLeft);
            String cardNum = "";
            if (TextUtils.isEmpty(datas.card_number)) {
                cardNum = "待选择油卡";
            } else {
                cardNum = datas.card_number;
            }
            Spanned infoRight = Spans.with(this).font(cardNum, x26, 0xff999999).
                    font("\n" + datas.periods + "个月", x26, 0xff999999).
                    font("\n" + first_time, x26, 0xff999999).
                    font("\n" + datas.money + "元", x26, 0xff999999).
                    font("\n" + datas.coupon_money, x26, 0xff999999).
                    font("\n" + datas.git + "%", x26, 0xff999999).
                    font("\n" + Arith.mul(Float.valueOf(datas.sale), 0.1) + "折", x26, 0xff999999).
                    font("\n" + Arith.add(Arith.add(Double.valueOf(datas.total_money), Double.valueOf(datas.git_value)),  Double.valueOf(datas.coupon_money))+ "元", x26, 0xff999999).
                    font("\n" + datas.total_money + "元", x26, 0xff999999).
                    font("\n" + datas.pay_money + "元", x26, 0xffFB5E01).
                    build();
            txtInfoRight.setText(infoRight);


            //        ===================================================快速充值===================================================
        } else if (datas.type.equals("2")) {
            //        ===================================================分期充值===================================================
            Spanned money = Spans.with(this).font("￥" + datas.pay_money, getResources().getDimensionPixelSize(R.dimen.x32), 0xffFB5E01).style(Typeface.BOLD).
                    font(" 多赠送" + datas.git + "%(即" + datas.git_value + "元)", getResources().getDimensionPixelSize(R.dimen.x22), 0xff999999).
                    build();
            txtContent.setText(money);


            Spanned infoLeft = Spans.with(this).font("加油卡卡号", x26, 0xff999999).
                    font("\n套餐时长", x26, 0xff999999).
                    font("\n首笔到账时间", x26, 0xff999999).
                    font("\n每月应得", x26, 0xff999999).
                    font("\n加油包", x26, 0xff999999).
                    font("\n每月多赠送", x26, 0xff999999).
                    font("\n折扣幅度", x26, 0xff999999).
                    font("\n应到账总额", x26, 0xff999999).
                    font("\n应付金额", x26, 0xff999999).
                    font("\n实际付款金额", x26, 0xff333333).
                    build();
            txtInfoLeft.setText(infoLeft);
            String cardNum = "";
            if (TextUtils.isEmpty(datas.card_number)) {
                cardNum = "待选择油卡";
            } else {
                cardNum = datas.card_number;
            }
            Spanned infoRight = Spans.with(this).font(cardNum, x26, 0xff999999).
                    font("\n" + datas.periods + "个月", x26, 0xff999999).
                    font("\n" + first_time, x26, 0xff999999).
                    font("\n" + datas.money + "元", x26, 0xff999999).
                    font("\n" + datas.coupon_money, x26, 0xff999999).
                    font("\n" + datas.git + "%", x26, 0xff999999).
                    font("\n" + Arith.mul(Float.valueOf(datas.sale), 0.1) + "折", x26, 0xff999999).
                    font("\n" +  Arith.add(Arith.add(Double.valueOf(datas.total_money), Double.valueOf(datas.git_value)),  Double.valueOf(datas.coupon_money)) + "元", x26, 0xff999999).
                    font("\n" + datas.total_money + "元", x26, 0xff999999).
                    font("\n" + datas.pay_money + "元", x26, 0xffFB5E01).
                    build();
            txtInfoRight.setText(infoRight);

            //        ===================================================分期充值===================================================
        }

    }

    private String getOrderType(String type) {
        switch (type) {
            case "1":
                return "快速充值";
            case "2":
                return "分期充值";
            default:
                return "";
        }
    }

    private String getStatus(String status) {
        switch (status) {
            case "-2":
                return "失效";
            case "-1":
                return "失败";
            case "0":
                return "待支付";
            case "1":
                return "完成";
            case "2":
                return "已付款";
            case "3":
                return "加油中";
            default:
                return "";
        }
    }

    private void init() {
        oilChangeDialog = new OilChangeDialog(this);

        oilChangeDialog.setDialogClickListener(new OilChangeDialog.DialogDefaultClickListener() {
            @Override
            public void confirm(String id, String ctype, String card_number) {
                getBindOrderCard(id, oilChangeDialog.getOrderNo());
            }

            @Override
            public void cancel() {

            }
        });
        x26 = getResources().getDimensionPixelSize(R.dimen.x26);
        txtTitle.setText("订单详情");
        String order_number = getIntent().getStringExtra("order_number");
        getOrderDetail(order_number);

    }

    public void getBindOrderCard(String id, String order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        BindOrderOilCardBean bean = new BindOrderOilCardBean();
        bean.oilcard_id = id;
        bean.order_no = order_no;
        Api.api_service.getBindOrderOilCard(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "绑定成功");
                    finish();
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(OilcardAddSuccess event) {
        finish();
    }

    public void getAccountList(String order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getOilcardList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    oilChangeDialog.setIsFromOrder(true, order_no);
                    oilChangeDialog.setData(result.datas);
                    oilChangeDialog.show();
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.layout_no_card, R.id.btn_back, R.id.btn_buy, R.id.btn_two})
    public void onViewClicked(View view) {
        switch (view.getId()) {
//            case R.id.layout_recharge_detail:
//                if (periodsData != null && periodsData.size() != 0)
//                    Dialog.showRechargeDetailDialog(this, periodsData, new Dialog.DialogDefaultClickListener() {
//                        @Override
//                        public void confirm() {
//
//                        }
//
//                        @Override
//                        public void cancel() {
//
//                        }
//                    });
//                break;
            case R.id.layout_no_card:
                Intent intent2 = new Intent(this, OilCardAddActivity.class);
                intent2.putExtra("add_order", true);
                intent2.putExtra("order_no", orderNo);
                startActivity(intent2);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_two:
                if (UI.toString(btnTwo).equals("删除订单")) {
                    Dialog.showDefaultDialog(this, "", "确定要删除该订单吗？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            getOrderDelete(orderNo);
                        }

                        @Override
                        public void cancel() {

                        }
                    });

                } else {
                    Util.startActivity(this, ChatCenterActivity.class);
                }

                break;
            case R.id.btn_buy:
                if (UI.toString(btnBuy).equals("返现记录")) {
                    Util.startActivity(this, ReturnCashActivity.class);
                    finish();
                } else if (UI.toString(btnBuy).equals("去付款")) {
                    Intent intent = new Intent(this, OilcardOrderPayMoneyActivity.class);
                    intent.putExtra("order_no", totalData.order_no);
                    intent.putExtra("sale_money", totalData.pay_money + "");
                    if (rechargeType.equals("1")) {
                        intent.putExtra("is_now_oil", true);
                    } else if (rechargeType.equals("2")) {
                        intent.putExtra("is_now_oil", false);
                    }
                    startActivity(intent);
                    finish();
                } else if (UI.toString(btnBuy).equals("重新购买")) {
                    if (totalData.type.equals("1")) {
                        Util.startActivity(this, NowRechargeActivity.class);
                    } else {
                        Util.startActivity(this, PacketRechargeActivity.class);
                    }
                    finish();
                } else if (UI.toString(btnBuy).equals("再次购买")) {
                    if (totalData.type.equals("1")) {
                        Util.startActivity(this, NowRechargeActivity.class);
                    } else {
                        Util.startActivity(this, PacketRechargeActivity.class);
                    }
                    finish();
                } else if (UI.toString(btnBuy).equals("重新购买")) {
                    Util.startActivity(this, PacketRechargeActivity.class);
                    finish();
                } else if (UI.toString(btnBuy).equals("选择油卡")) {
                    getAccountList(orderNo);
//                    Intent intent3 = new Intent(this, OilCardAddActivity.class);
//                    intent3.putExtra("add_order", true);
//                    intent3.putExtra("order_no", orderNo);
//                    startActivity(intent3);
//                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
//                    finish();
                }

                break;
        }
    }


}
